<?php

namespace app\controllers;

use app\librarys\BaseController;
use app\models\Department;
use app\models\FunctionPoint;
use app\models\Institution;
use app\models\Manager;
use app\models\Role;
use yii\data\Pagination;
use app\models\Permission;

class SystemController extends BaseController
{
    /**
     * 管理员列表
     * @return string
     */
    public function actionManagerList()
    {
        $currentInstitutionCode = Manager::getCurrentManager()['institution_code'];//当前用户登陆机构
        //20161026修改非0机构也可查询下级机构数据
        $institutionCode = \Yii::$app->request->get('institution_code', '');

        $pageSize = 10;
        if ($institutionCode == '') {
            //登陆用户为0机构下的 未选择机构则查询所有数据 否则则查询登陆用户所属机构及下级机构数据
            if (Permission::isSystemAdmin()) {
                $totalCount = Manager::getCount();
            } else {
                $totalCount = Manager::getSelfChildrenCount($currentInstitutionCode);
            }
        } else {
            $totalCount = Manager::getCountByInstitution($institutionCode);
        }

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        if ($institutionCode == '') {
            //登陆用户为0机构下的 未选择机构则查询所有数据 否则则查询登陆用户所属机构及下级机构数据
            if (Permission::isSystemAdmin()) {
                $items = Manager::getList($pagination->offset, $pagination->limit);
            } else {
                $items = Manager::getSelfChildrenList($currentInstitutionCode, $pagination->offset, $pagination->limit);
            }
        } else {
            $items = Manager::getListByInstitution($institutionCode, $pagination->offset, $pagination->limit);
        }

        $roleList = Role::getAllEnabledList();

        $institutions = null;
        if (Permission::isSystemAdmin()) {
            $institutions = Institution::getAllEnabledListWithHierarchy('0');
        } else {
            $institutions = Institution::getAllEnabledSelfChildren($currentInstitutionCode);
        }

        return $this->render('manager-list',
            ['items' => $items,
                'pagination' => $pagination,
                'roleList' => $roleList,
                'institutions' => $institutions,
                'institution_code' => $institutionCode,
                'currentInstitutionCode' => $currentInstitutionCode]);
    }

    /**
     * 新增管理员
     * @return string
     */
    public function actionAddManagerHandler()
    {
        $manager = \Yii::$app->request->post();

        $status = 0;
        $message = '';

        if ($manager['account'] == null || $manager['account'] == '') {
            $status = 1;
            $message = '创建失败，账号不能为空！';
        } else if ($manager['password'] == null || $manager['password'] == '') {
            $status = 1;
            $message = '创建失败，密码不能为空！';
        } else {
            $isRepeat = Manager::checkManagerAccountIsRepeat($manager['account']);
            if ($isRepeat) {
                $status = 1;
                $message = '创建失败，账号不能重复！';
            } else {
                $result = Manager::add($manager);
                if ($result <= 0) {
                    $status = 1;
                    $message = '创建失败，请联系开发人员！';
                }
            }
        }

        return $this->renderJson(null, $status, $message);

    }

    /**
     * 管理员详情
     * @return string
     */
    public function actionManagerDetailPartview()
    {
        $this->layout = false;

        $managerId = \Yii::$app->request->post('manager_id');
        $item = Manager::getDetail($managerId);

        $institutions = Institution::getAllEnabledListWithHierarchy('0');

        $roleList = Role::getAllEnabledList();

        //获取部门department_id
        $department_id = '';
        $de = Department::getDepartmentByManagerId($managerId);
        if ($de != null) {
            $department_id = $de['id'];
        }

        $departments = null;
        $departments = Department::getListTree($item['institution_code']);
        return $this->render('manager-detail-partview',
            [
                'item' => $item,
                'institutions' => $institutions,
                'roleList' => $roleList,
                'department_id' => $department_id,
                'departments' => $departments
            ]);
    }

    /**
     * 修改管理员
     * @return string
     */
    public function actionModifyManagerHandler()
    {
        $manager = \Yii::$app->request->post();

        $result = Manager::modify($manager);
        if ($result > 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '修改失败');
        }

    }

    /**
     * 系统功能点
     * @return string
     */
    public function actionFunctionPointList()
    {
        $items = FunctionPoint::getList();

        return $this->render('function-point-list', ['items' => $items]);
    }

    /**
     * 系统功能点详情
     * @return string
     */
    public function actionGetFunctionPointHandler()
    {
        $id = \Yii::$app->request->post('id');
        $item = FunctionPoint::get($id);

        if ($item == null) {
            return $this->renderJson(null, 100, '无此数据!');
        } else {
            return $this->renderJson($item);

        }
    }

    /**
     * 新增功能点
     * @return string
     */
    public function actionAddFunctionPointHandler()
    {
        $data = \Yii::$app->request->post();

        $result = FunctionPoint::add($data);
        if ($result > 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '创建失败');
        }
    }

    /**
     * 编辑功能点
     * @return string
     */
    public function actionEditFunctionPointHandler()
    {
        $data = \Yii::$app->request->post();

        $result = FunctionPoint::add($data);
        if ($result > 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '创建失败');
        }
    }

    /**
     * 删除功能点
     * @return string
     */
    public function actionDeleteFunctionPointHandler()
    {
        $functionPointId = \Yii::$app->request->post('function_point_id');

        $result = FunctionPoint::delete($functionPointId);
        if ($result > 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '删除失败');
        }
    }

    /**
     * 角色配置
     * @return string
     */
    public function actionRoleList()
    {
        $pageSize = 10;
        $totalCount = Role::getCount();

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        $items = Role::getList($pagination->offset, $pagination->limit);

        $functionPointItems = FunctionPoint::getList();

        return $this->render('role-list', ['items' => $items, 'pagination' => $pagination, 'functionPointItems' => $functionPointItems]);
    }

    /**
     * 角色详情
     * @return string
     */
    public function actionRoleSetPartview()
    {
        $roleId = \Yii::$app->request->post('role_id');
        $item = Role::getDetail($roleId);
        $functionPointItems = FunctionPoint::getList();
        return $this->renderPartial('role-set-partview', ['item' => $item, 'functionPointItems' => $functionPointItems]);
    }

    /**
     * 新增、修改角色
     * @return string
     */
    public function actionSetRoleHandler()
    {
        $role = \Yii::$app->request->post();

        $result = Role::set($role);
        if ($result > 0) {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '创建失败');
        }
    }

    public function actionMenuSetting()
    {
        return $this->render('menu-setting');
    }

    /**
     * 个人信息
     * @return string
     */
    public function actionPersonInfoPartview()
    {
        $this->layout = false;

        $session = \Yii::$app->session;
        $current_console_user = $session->get(Manager::SessionKey);

        //$managerId = \Yii::$app->request->post('manager_id');
        $item = Manager::getDetail($current_console_user['id']);

        //$institutions = Institution::getAllEnabledList();

        //$roleList = Role::getAllEnabledList();

        return $this->renderPartial('person-info-partview', ['item' => $item]);
        //return $this->render('person-info', ['item' => $item, 'institutions' => $institutions, 'roleList' => $roleList]);
    }

    /**
     * 修改个人信息
     * @return string
     */
    public function actionModifyManagerInfoHandler()
    {
        $manager = \Yii::$app->request->post();

        $result = Manager::modifyInfo($manager);
        if ($result == '0') {
            return $this->renderJson(null);
        } else {
            return $this->renderJson(null, 1, '修改失败');
        }
    }

    /**
     * 修改密码
     * @return string
     */
    public function actionModifyPasswordHandler()
    {
        //----------当前登录用户-----------------------------------------
        $session = \Yii::$app->session;
        $current_console_user = $session->get(Manager::SessionKey);
        //----------------------------------------------------------------

        $password = \Yii::$app->request->post();
        $result = 0;
        if (md5($password['oldPassword']) == $current_console_user['password']) {
            $result = Manager::modifyPassword($current_console_user['id'], $password['newPassword']);
        } else {
            $result = 1;
        }
        return $this->renderJson(null, $result, $result);
    }

    /**
     * 重置密码
     * @return string
     */
    public function actionModifyPasswordByManagerHandler()
    {
        $manageId = \Yii::$app->request->post('manageId');
        $newPassword = \Yii::$app->request->post('newPassword');

        $result = Manager::modifyPassword($manageId, $newPassword);

        return $this->renderJson(null, $result, $result);
    }
}